package com.danieltoms.gcSync.screens;

import java.util.Enumeration;

import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;

import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EmailAddressEditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.PasswordEditField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.danieltoms.gcSync.GcSync;
import com.danieltoms.gcSync.GcSyncStore;
import com.danieltoms.gcSync.contact.BBContact;
import com.danieltoms.gcSync.google.GoogleLoginException;
import com.danieltoms.gcSync.google.feed.GoogleClientLoginFeed;
import com.danieltoms.gcSync.resources.GcSyncResResource;

public class LoginScreen extends MainScreen implements FieldChangeListener
{
        private EmailAddressEditField m_emailField = null;
        private PasswordEditField m_passwordField = null;
        private ButtonField m_save = null;

        private boolean m_failed = false;
        private static boolean authenticated = false;

        private MenuItem m_helpItem = new MenuItem(GcSync.getMessages().getMessage(GcSyncResResource.MENU_HELP), 10, 5)
        {
                public void run()
                {
                        // onClose();
                }
        };

        private MenuItem m_closeItem = new MenuItem(GcSync.getMessages().getMessage(GcSyncResResource.MENU_CLOSE), 20, 10)
        {
                public void run()
                {
                        close();
                }
        };

        protected void makeMenu(Menu menu, int instance)
        {
                menu.add(m_helpItem);
                menu.addSeparator();
                menu.add(m_closeItem);
        }

        public LoginScreen()
        {
                super();

                drawScreen();

        }

        LoginThread m_thread = null;

        private void drawScreen()
        {
                // add title
                setTitle(new LabelField(GcSync.getMessages().getMessage(GcSyncResResource.LOGIN_TITLE), LabelField.ELLIPSIS
                        | LabelField.USE_ALL_WIDTH));

                // add sign in message
                this
                        .add(new RichTextField(GcSync.getMessages().getMessage(GcSyncResResource.LOGIN_TITLE),
                                Field.NON_FOCUSABLE));

                // add email field label
                // String email = "Email:";
                // this.add(new RichTextField(email,new int[] {0,email.length()},new
                // byte[] {0},new Font[] {Font.getDefault().derive(Font.BOLD)},0));

                m_emailField = new EmailAddressEditField(GcSync.getMessages().getMessage(GcSyncResResource.LOGIN_FIELD_EMAIL),
                        "gcsync@gmail.com");
                this.add(this.m_emailField);

                m_passwordField = new PasswordEditField(
                        GcSync.getMessages().getMessage(GcSyncResResource.LOGIN_FIELD_PASSWORD), "dtoms40969");
                this.add(this.m_passwordField);

                m_save = new ButtonField(GcSync.getMessages().getMessage(GcSyncResResource.LOGIN_BUTTON_SIGNIN),
                        ButtonField.CONSUME_CLICK);
                // m_save.setEditable(false);
                m_save.setChangeListener(this);
                this.add(m_save);

        }

        public boolean keyChar(char key, int status, int time)
        {
                String email = m_emailField.getText();
                String pass = m_passwordField.getText();
                // button is disabled until a reasonable email address is entered and a
                // password
                if (!m_save.isEditable())
                {

                        if (email.indexOf("@") != -1 && email.indexOf(".") != -1 && pass != null)
                                m_save.setEditable(true);
                }

                if (key == Characters.ESCAPE)
                {
                        System.out.println("Escape pressed");
                        return true;
                }

                return super.keyChar(key, status, time);
        }

        public void fieldChanged(Field arg0, int arg1)
        {
                // if save button pressed
                if (arg0 == this.m_save)
                {
                        String email = this.m_emailField.getText().trim();
                        String password = this.m_passwordField.getText().trim();

                        LoginThread t = new LoginThread(this, email, password);
                        t.start();
                        _popup = new LoginPopup();
                        UiApplication.getUiApplication().pushScreen(_popup);

                }
        }

        public LoginPopup _popup = null;

        public LoginPopup getLoginPopup()
        {
                return _popup;
        }

        public class LoginPopup extends PopupScreen
        {

                public boolean keyChar(char key, int status, int time)
                {

                        if (key == Characters.ESCAPE)
                        {
                                // we close the popup, but we may have a thread pending
                                // but we synchronize below to solve issues with that
                                close();

                                return true;
                        }

                        return super.keyChar(key, status, time);
                }

                public LoginPopup()
                {
                        super(new VerticalFieldManager());

                }
        }

        public class LoginThread extends Thread
        {

                GoogleClientLoginFeed _gcl = null;

                String _email = null;
                String _password = null;
                LoginScreen _loginScreen = null;

                public LoginThread(LoginScreen loginScreen, String email, String password)
                {

                        _email = email;
                        _password = password;
                        _loginScreen = loginScreen;
                }

                public void run()
                {

                        synchronized (UiApplication.getEventLock())
                        {
                                _loginScreen.getLoginPopup().add(
                                        new RichTextField(GcSync.getMessages().getMessage(GcSyncResResource.LOGIN_MESSAGE_CONNECTING,
                                                _email), null, null, null, Field.NON_FOCUSABLE));
                        }
                        // finally do the real login
                        _gcl = new GoogleClientLoginFeed();
                        authenticated = false;
                        try
                        {
                                authenticated = _gcl.authenticate(_email, _password);
                        }
                        catch (GoogleLoginException e2)
                        {
                                // TODO Auto-generated catch block
                                throw new RuntimeException(e2.getMessage());
                        }

                        if (authenticated)
                        {

                                /*

                                ContactList contacts;
                                try
                                {
                                        contacts = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST,
                                                        PIM.READ_WRITE);

                                        Enumeration e = contacts.items();

                                        while (e.hasMoreElements())
                                        {
                                                BBContact bc = new BBContact((Contact) e.nextElement());

                                                String lastName = bc.getFamilyName();
                                                if (lastName != null && !lastName.equals(""))
                                                {
                                                        System.out.println("flattening lastname: " + lastName);
                                                        String firstName = bc.getGivenName();
                                                        bc.setFamilyName(firstName + "" + lastName);
                                                        bc.commit();
                                                }
                                        }
                                }
                                catch (PIMException e1)
                                {
                                        // TODO Auto-generated catch block
                                        throw new RuntimeException(e1.getMessage());
                                }
                                 */
                                GcSyncStore.instance().storeEmail(_email);
                                GcSyncStore.instance().storePassword(_password);
                                GcSyncStore.instance().commit();

                                ((GcSync) UiApplication.getUiApplication()).addContactListener();

                                synchronized (UiApplication.getEventLock())
                                {
                                        _loginScreen.getLoginPopup().close();
                                        _loginScreen.close();
                                }
                        } // end run method
                        else
                        {
                                synchronized (UiApplication.getEventLock())
                                {
                                        _loginScreen.getLoginPopup().close();
                                }

                                UiApplication.getUiApplication().invokeLater(new Runnable()
                                {
                                        public void run()
                                        {
                                                Dialog.alert("Login failure: " + _gcl.getErrorCode());
                                        }
                                });

                        }

                } // end inner class
        }
}
